import { CSSBuilder, StyleResetContext, css } from './css';
import tpl from './style.css.tpl?raw';

const resetStyle = (
  context: Partial<StyleResetContext>,
  domReady: boolean,
  head?: string | string[] | null,
  foot?: string | string[] | null,
): void => {
  const d = document;
  const id = `__reset_style_${new Date().valueOf()}_${Math.floor(Math.random() * 100000)}`;
  if (d == null || d.getElementById(id)) return;

  const execute = () => {
    try {
      const builder = (new CSSBuilder(context)).appendCSS(head).appendCSS(tpl).appendCSS(foot);
      const css = builder.build();
      if (css !== '') {
        const node = d.createElement('style');
        node.setAttribute('id', id);
        node.appendChild(d.createTextNode(css));
        (d.head || d.querySelector('head') || d.documentElement).appendChild(node);
      }
    } catch (err) {
      // @ts-ignore
      console.warn(`inject reset styles error: ${err.message}`);
    }
  };
  if (domReady) {
    d.addEventListener('DOMContentLoaded', function () {
      execute();
    });
  } else {
    execute();
  }
};

resetStyle(
  {
    rootFont: [
      'Roboto',
      'PingFang SC',
    ],
    monoFont: [
      'JetBrains Mono',
      'PingFang SC',
      // 'Source Han Mono',
    ],
    boldFont  : [
      // 'Source Serif Pro SemiBold',
      // 'Noto Serif SC SemiBold',
      'Roboto',
      'PingFang SC',
    ],
    rootWeight: 300,
    uiWeight  : 300,
    monoWeight: 300,
    boldWeight: 400,
    textStrokeWidth: '0.020em',
    boldStrokeWidth: '0.030em',
  },
  false,
  null,
  css`
    @font-face {
      font-family: monospace;
      src: local("JetBrains Mono");
    }

    pre a, code a {
      font-family: var(--reset-mono-font) !important;
      font-weight: var(--reset-mono-weight) !important;
    }

    // for github
    .blob-code, .blob-code span, .blob-num, .blob-num:before {
      font-family: var(--reset-mono-font) !important;
      font-weight: var(--reset-mono-weight) !important;
    }
  `,
);

